﻿using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Microsoft.Expression.Framework.AddIn;
using System.Windows;
using Microsoft.Expression.Framework;
using Microsoft.Expression.Framework.Commands;
using Microsoft.Expression.Framework.UserInterface;
using System.Windows.Input;
using System.IO;
using System.Reflection;
using System.Windows.Data;

namespace BlendPluginManager
{
    public enum BlendMenus
    {
        File = 0,
        Edit = 1,
        View = 2,
        Object = 3,
        Project = 4,
        Tools = 5,
        Window = 6,
        Help = 7
    }
    [AddInDescription("Sorskoot - Blend Plugin Manager", AddInCategory.Tool)]
    public class BlendPluginManager:CommandTarget, IAddIn
    {
        #region IAddIn Members

        private IApplicationService CurrentApplicationService;
        private PluginsList MyPluginsList;
        
        private ObservableCollection<AddInDescriptor> AvailableAddins;
 
        public void Initialize(IApplicationService applicationService)
        {
            CurrentApplicationService = applicationService;

            MyPluginsList = new PluginsList();
            MyPluginsList.RescanButton.Click += new RoutedEventHandler(RescanButton_Click);
            
            CurrentApplicationService.CommandService.AddTarget(this);

            ICommandBarMenu toolsMenu = ((ICommandBarMenu)CurrentApplicationService.
                CommandBarService.CommandBars[0].Items[(int)BlendMenus.Tools]);
        
            if (CurrentApplicationService.WindowService.PaletteRegistry["PluginsList"] == null)
                CurrentApplicationService.WindowService.RegisterPalette("PluginsList", MyPluginsList, "Loaded Plugins");

            var workspace = (Workspace)CurrentApplicationService.WindowService.ActiveWorkspace;
            var palette = workspace.AddPalette("PluginsList", workspace.LeftPaletteGroup);

            palette.ShowCloseButton = true;
            palette.CanCollapse = false;
            palette.CanResize = true;
            palette.CanClose = true;
            palette.IsFloating = true;
            palette.Height = 400;
            palette.Width = 500;
            palette.IsVisible = false;
            palette.SetIsSelectedAsynchronously(false);

            PluginManagerCommand PMCommand = new PluginManagerCommand(palette);
            KeyBinding PMCommandBinding = new KeyBinding(PMCommand, Key.None, ModifierKeys.None);
            this.AddCommand("PluginManager", PMCommand);

            toolsMenu.Items.AddSeparator();
            toolsMenu.Items.AddCheckBox("PluginManager", "Plugin Manager", PMCommandBinding);
  
        }

        void RescanButton_Click(object sender, RoutedEventArgs e)
        {            
           // ScanDirectory();
        }

        private void ScanDirectory()
        {            
            AvailableAddins = new ObservableCollection<AddInDescriptor>();

            var fullp = Path.GetFullPath(".\\AddIns"); // first, get the full path of the "AddIns" Subdir
            var Files = Directory.GetFiles(fullp, "*.dll"); // Read all .DLLs in this dir
            foreach (var file in Files)
            {
                Assembly assembly = Assembly.LoadFile(file);                       
                foreach (var type in assembly.GetTypes())
                {
             
                    if (type.IsClass && type.IsPublic)
                    {
                        if (type.GetInterface("IAddIn") != null)
                        {
                            var custAtr = assembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), (true));

                            AvailableAddins.Add(new AddInDescriptor()
                            {
                                Name = assembly.GetName().Name,
                                Description = ((AssemblyDescriptionAttribute)assembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), (true))[0]).Description,
                                Category = ((AddInDescriptionAttribute)type.GetCustomAttributes(typeof(AddInDescriptionAttribute),true)[0]).Category
                            });
                            CurrentApplicationService.AddInService.LoadAddInsFromAssembly(assembly);
                           //CurrentApplicationService.AddInService.LoadAddIn(assembly.GetType());
                        }
                    }
                    
                };
                //AddInDescriptionAttribute Attr = (AddInDescriptionAttribute)types[0].GetCustomAttributes(false)[0];
                MyPluginsList.AvailablePlugins.ItemsSource = AvailableAddins;
            }
        }

        
        public void ShuttingDown()
        {
            //throw new NotImplementedException();
        }

        public void StartupComplete()
        {
            ScanDirectory();
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
          //  throw new NotImplementedException();
        }

        #endregion
    }
}
